<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <page-filter
      v-model:query="filterInfo.query"
      :filter-list="filterInfo.list"
    ></page-filter>
    <!-- 表格 -->
    <NewPageFilter :filter-btn="filterInfo.btnList"> </NewPageFilter>
    <table-container
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      :api="getReportPage"
      v-model:query="filterInfo.query"
      :field-list="tableInfo.fieldList"
      :handle="tableInfo.handle"
      :check-box="false"
      :tab-index="true"
      @handleEvent="handleEvent"
    ></table-container>
    <el-upload
      style="opacity: 0"
      ref="importXmlRef"
      :headers="uploadInfo.headers"
      :data="uploadInfo.data"
      :show-file-list="false"
      :on-error="uploadError"
      :on-success="importProduct"
      :before-upload="beforeProductUpload"
      :action="uploadInfo.action"
    >
      <el-button type="warning" id="inportXmlBtn" ref="inportXmlBtnRef"
        >导入</el-button
      >
    </el-upload>
  </div>
</template>

<script setup name="reportListManager">
import {
  getReportPage,
  restoreReport,
  delReport,
  exportReportByName,
} from '@/api/report.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import axios from 'axios'
const store = useStore()
const { proxy } = getCurrentInstance()
const uploadInfo = ref({
  action: null,
  headers: {
    Authorization: store.state.user.token,
  },
  data: {},
  loading: {},
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    sort: 'create_time desc',
  },
  list: [
    {
      type: 'input',
      label: '名称',
      value: 'keywords',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      show: proxy.$permission('report:add'),
      event: create,
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    { label: '文件名', value: 'name' },
    { label: '类型', value: 'type' },
    { label: '创建人', value: 'createBy' },
    { label: '创建时间', value: 'createTime' },
    { label: '修改人', value: 'updateBy' },
    { label: '修改时间', value: 'updateTime' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '180',
    btList: [
      {
        label: '设计',
        type: 'button',
        event: design,
        show: proxy.$permission('report:design'),
      },
      {
        label: '导入',
        type: 'button',
        event: importXml,
        show: proxy.$permission('report:import'),
      },
      {
        label: '导出',
        type: 'button',
        event: exportXml,
        show: proxy.$permission('report:export'),
      },
      {
        label: '删除',
        type: 'button',
        event: del,
        show: proxy.$permission('report:del'),
      },
      {
        label: '恢复缺省',
        type: 'button',
        event: recover,
        show: proxy.$permission('report:recover'),
      },
    ],
  },
})
console.log(4444444)

// 获取列表
function getList() {
  console.log(5555)
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  console.log(666)
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}

function design(val) {
  proxy.$store.dispatch('tabsView/updateIsCloseDesign', false)
  const name = `slip-${val.name}`
  const url = `/ureport/designer?_u=${name}`
  proxy.$store.commit('SET_UREPORT_URL', url)
  localStorage.setItem('ureportDesigner', url)
  proxy.$router.push(`/report/design?_u=${name}`)
}

// 创建
function create() {
  proxy.$store.commit('SET_UREPORT_URL', '/ureport/designer')
  localStorage.setItem('ureportDesigner', '/ureport/designer')
  proxy.$router.push('/report/design')
}

async function del(row) {
  const ok = await ElMessageBox.confirm(
    '是否确认删除报表名称为"' + row.name + '"的数据项?'
  )
  if (ok) {
    // 请求删除接口
    const res = await delReport(row.name)
    if (res.code === 200) {
      proxy.$message.success('删除成功')
      search()
    }
  }
}

/**恢复缺省 */
function recover(row) {
  ElMessageBox.confirm(
    '是否确认重置报表名称为"' + row.name + '"的数据项?'
  ).then(() => {
    restoreReport(row.name).then(() => {
      proxy.$message.success('重置成功')
    })
  })
}

// 触发事件
function handleEvent(event, data) {
  switch (event) {
    // 对表格获取到的数据做处理
    case 'tableCheck':
      tableInfo.value.selections = data
      break
  }
}

//导入
function importXml(row) {
  uploadInfo.value.data = { name: row.name }
  uploadInfo.value.action =
    axios.defaults.baseURL + '/report/import/xml/' + row.id
  let inportXmlBtnDom = document.getElementById('inportXmlBtn')
  if (inportXmlBtnDom) {
    inportXmlBtnDom.click()
  }
}

//导出
function exportXml(row) {
  //exportReportByName(row.name)
  window.open(
    axios.defaults.baseURL + '/report/export/xml?reportName=' + row.name
  )
}

function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xml']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}

function importProduct(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg || '导入成功！',
    })
    getList()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}

function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
</script>
